package com.franklin.ideaplugin.easytesting.common.utils;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

/**
 * @author Ye Junhui
 * @since 2023/5/15
 */
public class PortUtils {

    /**
     * 获取可用端口，默认20202
     * @return
     * @throws IOException
     */
    public static int getUsablePort() throws IOException {
        return getUsablePort(20202);
    }

    /**
     * 获取可用端口号
     * @param port
     * @return
     * @throws IOException
     */
    public static int getUsablePort(int port) throws IOException {
        boolean flag = false;
        Socket socket = null;
        InetAddress theAddress = InetAddress.getByName("127.0.0.1");
        try{
            socket = new Socket(theAddress, port);
            flag = true;
        } catch (IOException e) {
            //如果测试端口号没有被占用，那么会抛出异常，通过下文flag来返回可用端口
        } finally {
            if(socket!=null) {
                //new了socket最好释放
                socket.close();
            }
        }

        if (flag) {
            //端口被占用，port + 1递归
            port = port + 1;
            return getUsablePort(port);
        } else {
            //可用端口
            return port;
        }
    }
}
